<template>
  <div class="login">
    <!-- 主体 -->
    <div class="main-login">
      <!-- 左侧 -->
      <div class="main-login-left imageDisplay">
        <div>数字化助力管理升级</div>
      </div>
      <!-- 右侧 -->
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px" class="main-login-right">
        <div class="first">欢迎登录 管理</div>
        <div class="firstPC">
          <div class="title">欢迎登录 管理</div>
          <div class="watermark">{{ year }}</div>
        </div>
        <div class="second">选择一种方式登录</div>
        <el-form-item>
          <el-button size="medium" class="btnFirst" @click.native.prevent="handlessoLogin">
            <img src="../assets/images/haisumLogo.png" class="logoHaisum">
            <div>中国海诚统一认证平台</div>
          </el-button>
        </el-form-item>
        <div class="divided">————————————<i>或</i>———————————</div>
        <div>
          <el-form-item prop="username" style="margin-bottom: 24px;">
            <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="请输入账号">
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-tooltip
              v-model="capsTooltip"
              content="大写已打开"
              placement="left"
              manual
            >
              <el-input id="pwd" ref="password" v-model="loginForm.password" :type="passwordType" auto-complete="off" placeholder="请输入密码" @keyup.enter.native="handleLogin" @click.native="addInputListener" @keyup.native="addInputListener">
                <svg-icon slot="prefix" icon-class="lock-on" class="el-input__icon input-icon" />
              </el-input>
            </el-tooltip>
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
          <el-checkbox v-model="loginForm.rememberMe" class="remember">记住账号及密码</el-checkbox>
          <el-form-item>
            <el-button :loading="loading" size="medium" class="btnSecond" @click.native.prevent="handleLogin">
              <span v-if="!loading">登录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </el-form-item>
        </div>
        <SafeTip :is-bottom="false" :env="env" />
        <!-- 版本号 -->
        <div class="el-login-footer">海诚·云工场{{ majorVersion }}（版本号V{{ version }}）</div>
      </el-form>
    </div>
    <!--  防止刷新后主题丢失  -->
    <theme-picker v-show="false" />
  </div>
</template>

<script>
import { encrypt, decryptCloud, encryptCloud } from '@haisum-cloud/ui-components/packages/utils/rsaEncrypt'
import Config from '@/settings'
import Cookies from 'js-cookie'
import qs from 'qs'
import { systemParameterList } from '@/api/systemParameter'
import Package from '../../package.json'
import ThemePicker from '@/components/ThemePicker'
import SafeTip from '@haisum-cloud/ui-components/packages/safeTip'
import { mapGetters } from 'vuex'
export default {
  name: 'Login',
  components: {
    ThemePicker, SafeTip
  },
  data() {
    return {
      year: '.', // 大版本的时间
      env: process.env.VUE_APP_NODE_ENV || process.env.NODE_ENV,
      majorVersion: '',
      version: '',
      passwordType: 'password',
      cookiePass: '',
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '用户名不能为空' }],
        password: [{ required: true, trigger: 'blur', message: '密码不能为空' }]
      },
      loading: false,
      redirect: undefined,
      capsTooltip: false // 大写锁定关闭
    }
  },
  ...mapGetters([
    'pageParmas'
  ]),
  watch: {
    $route: {
      handler: function(route) {
        const data = route.query
        if (data && data.redirect) {
          this.redirect = data.redirect
          delete data.redirect
          if (JSON.stringify(data) !== '{}') {
            this.redirect = this.redirect + '&' + qs.stringify(data, { indices: false })
          }
        }
      },
      immediate: true
    }
  },
  created() {
    // 获取用户名密码等Cookie
    this.getCookie()
    // token 过期提示
    this.point()
    // 添加页面参数
    this.addPageParmas()
  },
  methods: {
    /* 对输入框keyup事件进行监听*/
    addInputListener(e) {
      if (e && e.getModifierState('CapsLock')) {
        this.capsTooltip = true
      } else {
        this.capsTooltip = false
      }
    },
    /* 密码显示与否切换*/
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    getCookie() {
      const username = Cookies.get('username')
      let password = Cookies.get('password')
      const rememberMe = Cookies.get('rememberMe')
      // 保存cookie里面的加密后的密码
      password = password === undefined ? this.loginForm.password : decryptCloud(password)
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password,
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
        code: ''
      }
    },
    // 登录中国海诚统一认证
    handlessoLogin() {
      // 判断是否星期三
      const date = new Date()
      const week = date.getDay()
      const hour = date.getHours()
      if (week === 3 || (week === 4 && hour < 20)) {
        this.$notify({
          title: '提示',
          message: '本周四20:00~24:00服务器停机维护，请及时保存文件！',
          type: 'warning',
          duration: 0
        })
      }
      window.location.href = process.env.VUE_APP_SSO_URL + '&state=' + appType + ','
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          code: this.loginForm.code
        }
        if (user.rememberMe) {
          Cookies.set('username', user.username, { expires: Config.passCookieExpires })
          Cookies.set('password', encryptCloud(user.password), { expires: Config.passCookieExpires })
          Cookies.set('rememberMe', user.rememberMe, { expires: Config.passCookieExpires })
        } else {
          Cookies.remove('username')
          Cookies.remove('password')
          Cookies.remove('rememberMe')
        }
        localStorage.setItem('username', user.username)
        localStorage.setItem('password', encryptCloud(user.password))
        user.password = encrypt(user.password)
        if (valid) {
          this.loading = true
          this.$store.dispatch('Login', user).then(() => {
            localStorage.setItem('ip', this.$store.getters.user.ip)
            this.loading = false
            this.$router.push({ path: this.redirect || '/' })
          }).catch((ex) => {
            this.loading = false
            if (ex.message.search('Cannot read properties of undefined') !== -1) {
              this.$notify({
                title: '提示',
                message: '访问失败，请检查网络环境！',
                type: 'error',
                duration: 5000
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    point() {
      const point = Cookies.get('point') !== undefined
      if (point) {
        this.$notify({
          title: '提示',
          message: '当前登录状态已过期，请重新登录！',
          type: 'warning',
          duration: 5000
        })
        Cookies.remove('point')
      }
    },
    updateVersion(params) {
      if (params && params['app_versions']) {
        const versionObject = JSON.parse(params['app_versions'].value)
        const currentVersionStr = versionObject['management']
        const versionArr = currentVersionStr.split('-')
        if (versionArr.length !== 2) return
        this.majorVersion = versionArr[0]
        this.version = versionArr[1]
        this.year = this.majorVersion.split('.').at(0)
      } else {
        this.majorVersion = Package.majorVersion
        this.version = Package.version
        this.year = Package.majorVersion.split('.').at(0)
      }
      localStorage.setItem('version', this.version)
    },
    // 添加页面参数
    addPageParmas() {
      systemParameterList().then(data => {
        const params = {}
        if (data) {
          data.map((item, index) => {
            const parameterValue = item.code
            params[parameterValue] = data[index]
          })
        }
        if (params) {
          localStorage.setItem('messageStore', JSON.stringify(params))
          // 更新数据
          this.$store.dispatch('page/addPageParmas', params)
          this.updateVersion(params)
        } else {
          this.updateVersion()
        }
        const val = params && params.skin_name && params.skin_name.value ? params.skin_name.value.split(',')[0] : '#409EFF'
        this.$store.dispatch('settings/changeSetting', {
          key: 'theme',
          value: val
        })
      }).catch(() => {
        const val = '#409EFF'
        this.$store.dispatch('settings/changeSetting', {
          key: 'theme',
          value: val
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" scoped lang="scss">
  .login {
    background-image: url("../assets/images/bg1.png");
    display: flex;
    justify-content: center;
    align-items: center;
    position:fixed;
    width:100%;
    height: 100%;
    background-size: 100% 100%;
  }

  .main-login {
    width: 1398px;
    height: 815px;
    display: flex;
    flex-flow: row nowrap;
    box-shadow: 4px 15px 18px -7px #bcbbba;
  }

  .main-login-left{
    width: 699px;
    height: 100%;
    background-image: url("../assets/images/bg2.png");
    border-radius: 12px 0px 0px 12px;
  }

  .main-login-left>div{
    color: #FFF;
    font-size: 28px;
    font-family: Microsoft YaHei;
    line-height: 22px;
    letter-spacing: 0.28px;
    text-align: center;
    margin-top: 667px;
  }

  .main-login-right{
    margin: 0 auto;
    width: 699px;
    height: 100%;
    background: #fff;
    padding: 0 167px 167px 166px;
    border-radius: 0px 12px 12px 0px;
  }

  .main-login-right>>>.el-input {
    height: 40px;
    background: #FBFCFD;
    border-radius: 3px;
    input {
      height: 40px;
      background: #FBFCFD;
      border-radius: 3px;
      padding-left:42px;
    }
    .el-input__inner:focus {
      outline: none;
      border-color: var( --ui-theme-color );
    }
  }
  .main-login-right>>>.input-icon {
    height: 18px;
    width: 18px;
    margin-left: 8px;
    margin-top: 12px;
  }

  .first{
    color: var(--text-icon-font-gy-190-primary, rgba(0, 0, 0, 0.90));
    font-size: 36px;
    font-family: Microsoft YaHei;
    font-weight: 600;
    margin-top: 140px;
  }
  .firstPC{
    margin-top: 92px;
    position: relative;
    width: 454px;
    .title{
      position: absolute;
      z-index: 1;
      top: 70px;
      color: var(--text-icon-font-gy-190-primary, rgba(0, 0, 0, 0.90));
      font-size: 36px;
      font-family: Microsoft YaHei;
      font-weight: 600;
    }
    .watermark {
      color: #f0f0f0;
      font-family: PingFang SC;
      font-size: 116px;
      font-weight: 500;
      text-align: right;
      min-width: 100px;
    }
  }

  .second{
    color: var(--text-icon-font-gy-260-secondary, rgba(0, 0, 0, 0.60));
    font-size: 14px;
    font-family: Microsoft YaHei;
    margin-top:30px;
    margin-bottom:31px;
  }

  .show-pwd {
    position: absolute;
    right: 11px;
    top: 6px;
    font-size: 16px;
    color: #889AA4FF;
    cursor: pointer;
    user-select: none;
  }

  .remember{
    color: var(--text-icon-font-gy-190-primary, rgba(0, 0, 0, 0.90));
    font-size: 14px;
    font-family: Microsoft YaHei;
    margin: 9px 0px 40px 0px;
  }

  .divided{
    color: #e7e7e7;
    font-size: 14px;
    font-family: Microsoft YaHei;
    height:62px;
  }

  .divided i{
    color: #000;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-style: normal;
  }

  .btnFirst{
    width: 366px;
    height: 50px;
    padding: 14px 93px;
    border-radius: 3px;
    color: #000128;
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 600;
    margin-bottom: 3px;
  }

  .logoHaisum{
    width: 20px;
    height: 20px;
    margin-right: 8px;
    float: left;
    margin-top: -2px;
  }

  .btnSecond{
    display: flex;
    height: 40px;
    width: 366px;
    padding: 8px 0px;
    justify-content: center;
    align-items: center;
    border-radius: 3px;
    background: var( --ui-theme-color );
    color: #FFF;
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 600;
    line-height: 24px;
  }

  .btnFirst.el-button:hover {
    background-color: #FEFFFF;
    border:1px solid var( --ui-theme-color );
    color: #000128;
  }

  .btnSecond.el-button:hover {
    background-color: var( --ui-theme-color );
    color: #FFF;
  }

  .el-login-footer {
    font-family: Microsoft YaHei;
    letter-spacing: -0.01px;
    color: var(--text-icon-font-gy-340-placeholder, rgba(0, 0, 0, 0.40));
    font-size: 14px;
    line-height: 22px;
    margin-top: 80px;
    text-align: center;
  }
  @media screen and (max-width: 1440px){
    .imageDisplay{
      display: none;
    }
    .firstPC{
      display: none;
    }
    .first{
      display: block;
    }
  }
  @media screen and (min-width: 1440px){
    .imageDisplay{
      display: block;
    }
    .firstPC{
      display: block;
    }
    .first{
      display: none;
    }
  }
</style>
